$("#pickdate").dateDropper({
	animate: false,
	format: 'Y-m-d',
	maxYear: '2020'
});
$("#picktime").timeDropper({
	meridians: false,
	format: 'HH:mm',
});

var app = angular.module('myApp', []);

//修改Angular的$httpProvider的默认处理方式，否则无法在PHP里使用_POST[]获取数据
app.config(function($httpProvider){
    $httpProvider.defaults.transformRequest=function(obj){
        var str=[];
        for(var p in obj){
            str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));
        }
        return str.join("&");
    };
    $httpProvider.defaults.headers.post={
        'Content-Type':'application/x-www-form-urlencoded'
    }
});

app.factory('shareDataService', function ($http, $q) {
     var service = {};
     var locationVar;
     //设置地理位置信息
     service.setLocation = function (location) {
        locationVar = location;
     }
     //返回地理位置信息
     service.getLocation = function () {
         return locationVar;
      }
      return service;
});
//发布页面控制器
app.controller('publishCtrl', function ($scope,shareDataService,$http,$compile) {
    //记录选择的任务类型
    $scope.typeVar = "none";
    $scope.taskAllocationVar = "none";
    $scope.aggregationVar = "none";
    $scope.worker_num = 1;

    $scope.location = shareDataService.getLocation;
    //根据选择的任务类型，从数据库获取任务类型对应的元数据
    $scope.setSelectedType = function(typeVar){
        $http({
            method:"post",
            url: ip + "getType.php",
            data:{
                selectedType: typeVar
            }
        }).success(function(data, status, headers, config){
            if (data.success) {
                //获取成功，解析字段并动态添加
                alert("获取类型信息成功 "+ data.msg);
                var fields = eval("(" + data.msg + ")");
                for(var field in fields){
                    alert(field + "=" + fields[field]);
                    var html;
                    if(field == "location"){
                        html = "<div class='input-group my-input'><span class='input-group-addon myspan'><i class='fa fa-snowflake-o'></i></span><input ng-click='turn2Select()' type='text' class='form-control myinput' ng-model='location' placeholder='" + fields[field] + "'></div><br>";
                    }
                    //html = "<div class='input-group my-input'><span class='input-group-addon my-radius-border'><i class='fa fa-snowflake-o'></i></span><input type='text' class='form-control my-radius-border' placeholder='输入" + fields[field] + "'></div><br>";
                    var template = angular.element(html);
                    var dynamicYwcpxElement = $compile(template)($scope);
                    var input_div = document.getElementById("input_div");
                    angular.element(input_div).append(dynamicYwcpxElement);
                }
            }else{
                alert("获取类型信息失败: " + data.msg);
            }
        })

    };

    $scope.turn2Select = function() {
        document.getElementById("publish_to_select").click();
    }

    //增加worker数量
    $scope.addNum = function(){
        $scope.worker_num++;
    };

    //减少worker数量
    $scope.decreaseNum = function(){
        if($scope.worker_num > 1){
            $scope.worker_num--;
        }
    };

});

//选择地理位置控制器
app.controller('selectLocCtrl', function ($scope,$http,shareDataService) {
    var selectedLoc = "";
    var latitude;
    var longitude;
    $scope.back2Publish = function(){
        //sessionStorage.setItem("selectedLoc", selectedLoc);
        shareDataService.setLocation(selectedLoc);
        document.getElementById("select_to_publish").click();
    }

    var onLocationError = function(error) {
        console.log('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
    }

    var onLocationSuccess = function (position) {

        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
        // 百度地图API功能
        var map = new BMap.Map("map");

        //利用百度地图API进行地理位置坐标转换（需要引入convertor.js这一文件）
        var gpsPoint = new BMap.Point(longitude, latitude);
        var geoc = new BMap.Geocoder();
        BMap.Convertor.translate(gpsPoint, 0, function (point) {
            geoc.getLocation(point, function (rs) {
                map.centerAndZoom(point, 18);
                map.addOverlay(new BMap.Marker(point)) ;

                var addComp = rs.addressComponents;
            });
        });

        //地图点击事件：显示所选择的地点
        map.addEventListener("click", function(e){
            var pt = e.point;
            geoc.getLocation(pt, function(rs){
                var addComp = rs.addressComponents;
                //var isConfirmed = Showbo.Msg.confirm("您所选择的地理位置是：" + addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
                var tempLoc = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                var isConfirmed = confirm("您所选择的地理位置是：" + tempLoc);
                if(isConfirmed){
                    selectedLoc = tempLoc;
                    map.clearOverlays();
                    map.addOverlay(new BMap.Marker(pt));
                }
            });
        });

        //输入提示
        function G(id) {
            return document.getElementById(id);
        }
        var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
                {"input" : "selectLoc"
                ,"location" : map
        });

        ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
            var str = "";
            var _value = e.fromitem.value;
            var value = "";
            if (e.fromitem.index > -1) {
                value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
            }
            str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

            value = "";
            if (e.toitem.index > -1) {
                _value = e.toitem.value;
                value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
            }
            str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
            G("searchResultPanel").innerHTML = str;
        });

        var myValue;
        ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
            var _value = e.item.value;
            myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
            G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
            selectedLoc = myValue;
            setPlace();
        });

        function setPlace(){
            map.clearOverlays();    //清除地图上所有覆盖物
            function myFun(){
                var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
                map.centerAndZoom(pp, 18);
                map.addOverlay(new BMap.Marker(pp));    //添加标注
            }
            var local = new BMap.LocalSearch(map, { //智能搜索
              onSearchComplete: myFun
            });
            local.search(myValue);
        }
    }

    getLocation();
    function getLocation(){
        navigator.geolocation.getCurrentPosition(onLocationSuccess,onLocationError, { enableHighAccuracy: true });
    }

});